
import * as $api from '../api/index'

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date,deadline=0) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()+deadline

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}



export function previewImage(current,urls){
  wx.previewImage({
    current: current, // 当前显示图片的http链接
    urls: urls, // 需要预览的图片http链接列表
    fail:err=>{console.log(err)}
  })
}

export function navigateTo(url){
  wx.navigateTo({
    url:url,
    fail(err){
      console.log(err)
    }
  })
}


export function redirectTo(url){
  wx.redirectTo({
    url:url,
    fail:err=>{
      console.log(err)
    }
  })
}

export function switchTab(url){
  wx.switchTab({
    url:url,
    fail:err=>{
      console.log(err)
    }
  })
}


export function showToast(title,icon="none",time=1500){
  wx.showToast({
    title:title,
    icon:icon,
    duration:time=="" ? 1500 :time
  })
}

export function showModal(title,content){
  let promise=new Promise((resolve ,reject) => {
    wx.showModal({
      title: title,
      content: content,
      success (res) {
        if (res.confirm) {
          resolve(true)
        } else if (res.cancel) {
           resolve(false)
        }
      },
      fail:err=>{
        reject(err)
      }
    })
  })
  return promise
}

//微信授权
async function bindGetUserInfo(info,baseUrl) {

  //判断是否允许授权，如果拒绝则无需绑定用户信息
  if(!info){
    return
  }

  wx.showLoading({
    title: '正在登录'
  })
  let data = '' //返回是否成功的标志

  //获取登录信息
  const r = await wx.login({})
  const code = r.code

  let invited_user_id = ""
  //本地找不到就为空
  if(wx.getStorageSync("invited_user_id")){
    invited_user_id = wx.getStorageSync("invited_user_id")
  }else{
    invited_user_id = ""
  }

  //获取用户信息
  const res = await wx.getUserInfo({})

  if(res.rawData && res.signature){
    let params = {
      raw_data: res.rawData,
      signature: res.signature,
      code: code,
      invited_user_id: invited_user_id //邀请人id
    }
    const result = await $api.wxAppLogin(params, baseUrl);
    if (result.data.level == 'success') {
      wx.setStorageSync('userToken', result.data.data);
      data = "success"
    } else {
      wx.showToast({
        title: result.data.message,
        icon: "none",
        duration: 1500
      })
    }
  }
  wx.hideLoading()
  return data
}

//获取个人信息
async function getUserInfos(baseUrl) {
  let userToken=wx.getStorageSync('userToken');
  if (userToken) {
    const res = await $api.getUserInfos({},baseUrl);
    if (res.data.level == 'success') {
      const userInfo = res.data.data
      wx.setStorageSync('user_id', userInfo.id);
      wx.setStorageSync('wx_openid', userInfo.wx_openid);
      wx.setStorageSync('photo_url', userInfo.user_info.photo_url)
      wx.setStorageSync('nickname', userInfo.user_info.nickname)
      return userInfo
    }
  }
}

//绑定手机号码
async function getPhoneNumber(e,baseUrl) {
  if(!e.detail.iv){
    return
  }
  let params = ''
  let level = ''

  try{
    await wx.checkSession({})
    params = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }

  } catch (err) {
    wx.showLoading({
      title: '正在获取'
    })
    let r = await wx.login({})
    wx.hideLoading()
    let code = r.code;

    params = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      code: code,
    }
  }

  level = await getWeChatPhone(params, baseUrl)
  return level
}

async function getWeChatPhone(params, baseUrl) {

  const phoneData = await $api.getWeChatPhone(params, baseUrl)

  if(phoneData.data.level == 'success') {
    if (phoneData.data.message == "获取成功") {
      let tempData = JSON.parse(phoneData.data.data)
      let phoneParams = {
        phone: tempData.phoneNumber,
      }
      const res = await $api.directBindingPhone(phoneParams, baseUrl)

      wx.showToast({
        title: res.data.message,
        icon: "none",
        duration: 1500
      })
      if (res.data.level == "success") {
        return 'success'
      }

    } else {
      wx.showToast({
        title: "获取失败,请重新获取",
        icon: "none",
        duration: 1500
      })
    }
  } else {
    wx.showToast({
      title: phoneData.data.message,
      icon: "none",
      duration: 1500
    })
  }
}

export default {
  formatNumber,
  formatTime,
  navigateTo,
  showToast,
  redirectTo,
  previewImage,
  switchTab,
  showModal,
  bindGetUserInfo,
  getUserInfos,
  getPhoneNumber
}
